<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <link rel="stylesheet" href="../css/style.css">
  <link rel="stylesheet" href="../css/tables.css">
  <title>后台管理系统</title>
</head>
<body>
  <div class="container">

    <div class="leftMenu">
      <div class="userAvatar">
        <img src="http://localhost:8080/upload/getImgByPath/1685625402999.jpg" alt="用户头像">
        <p id="accountName"></p>
        <p>超级管理员</p>
      </div>
      <a href="../index.html" class="selectMenuItem">
        主页
        <p class="dataCenterPage">数据中心</p>
      </a>
      <a  href="./tables.html" class="selectMenuItem active">
        表格
        <p class="tablePage">订单内容</p>
      </a>
      <a href="./destination.html" class="selectMenuItem">
        地图
        <p class="mapPage">工作室位置</p>
      </a>
    </div>

    <div class="rightContent">

      <div class="navBanner">
        <h2>欢迎进入后台管理系统</h2>
        <p id="outLogin">退出</p>
      </div>

      <div class="tableBanner">
        <div class="tableBannerFunction">
          <div>
            <h2>订单表格</h2>
            <p>表格 / 订单内容</p>
          </div>
          <div class="search">
            搜索商品：<input type="text" placeholder="请输入商品名称" id="productName">
            <button id="searchProductByName">搜索</button>
            <button id="resetProductByName">刷新数据</button>
          </div>
        </div>
        <div class="tableBannerAddData">
          <p><span class="tableBannerAddData">+</span>添加数据</p>
        </div>
      </div>

      <div class="tableContent">
        <table border="1" width="100%">
          <thead>
            <tr>
                <th>商品编号</th>
                <th>商品ID</th>
                <th>商品名称</th>
                <th>商品价格</th>
                <th>商品介绍</th>
                <th>商品图片</th>
                <th>创建时间</th>
                <th>操作</th>
            </tr>
          </thead>
          <tbody id="trData"></tbody>
        </table>
      </div>
      
    </div>
  </div>

  <div class="imagesContainer"></div>

  <div class="tableFormContainer">
    <div class="changeFormContent" style="display: none;">
      商品名称: <input type="text" name="name" id="changeTheName">
      商品价格: <input type="text" name="price" id="changeThePrice">
      <input type="submit" value="确认提交" id="submitFormData" style="display: block; margin: 10px auto 0;">
    </div>
  </div>

  <div class="tableFormContainer">
    <form class="addFormContent" style="display: none;" onsubmit="return addFormContentFun(this)">
        <legend>创建新的商品</legend>

        商品名称：<input type="text" name="name"><br>
        商品价格：<input type="text" name="price"><br>
        商品介绍：<input type="text" name="introduce"><br>
        商品详情：<input type="text" name="details"><br>
        商品图片：<input type="file" name="imagePatch">

        <input type="submit" value="提交" style="display: block; margin: 10px auto 0;">
    </form>
  </div>

  <div class="coverContent" style="display: none"></div>

  <script>
    window.onload = function() {
      if (!localStorage.getItem('username') &&  !localStorage.getItem('password')) {
        window.location.href="./login.html";
      }
    }
    
    const accountName = document.getElementById('accountName');
    const outLogin = document.getElementById('outLogin');
    const productName = document.getElementById('productName');
    const searchProductByName = document.getElementById('searchProductByName');
    const resetProductByName = document.getElementById('resetProductByName');
    const tableBannerAddData = document.querySelector('.tableBannerAddData');
    const trData = document.getElementById('trData');

    const coverContent = document.querySelector('.coverContent');
    
    const imagesContainer = document.querySelector('.imagesContainer');
    const tableFormContainer = document.querySelector('.tableFormContainer');
    const addFormContent = document.querySelector('.addFormContent');
    const changeFormContent = document.querySelector('.changeFormContent');
    
    let tableData = [];
    let nowIndex = 0;

    accountName.innerHTML = localStorage.getItem('username');
    
    function renderingStr(data) {
      let str = '';
      let getTheDate;
      
      for (let i = 0; i <= data.length - 1; i++) {
        getTheDate = timestampToTimeFun(data[i].createTime);
        str += `
              <tr align="center">
                <td>${i + 1}</td>
                <td>${data[i].id}</td>
                <td>${data[i].name}</td>
                <td>${data[i].price}</td>
                <td>${data[i].introduce}</td>
                <td><img src="${data[i].imagePatch}" onclick="showImagesFun('${data[i].imagePatch}')" /></td>
                <td>${getTheDate}</td>
                <td>
                  <button style="background-color: rgb(82, 167, 255)" onclick="operationFun(${i}, 'change')">修改</button>
                  <button style="background-color: rgb(247, 134, 134)" onclick="operationFun(${i}, 'delete')">删除</button>
                </td>
              </tr>`;
      }
        
      return str;
    }

    outLogin.addEventListener('click', () => {
      const msg = "是否退出登录？";
      if (confirm(msg) == true) {
        localStorage.removeItem('username');
        localStorage.removeItem('password');
        
        window.location.href="./login.html";
        return true;
      }
    })

    function getTableDataList() {
      let str = `<tr></tr>`;

      axios.get('http://localhost:8080/products/getProductInformationByLimit', {
        params: {
          offset: 0,
          size: 10
        }
      }).then(function (res) {
        tableData = res.data;
        trData.innerHTML = renderingStr(res.data);
      }).catch(function (err) {
        console.log(err);
      });
    }
    
    function timestampToTimeFun(timestamp) {
      let date = new Date(timestamp);

      let Y = date.getFullYear() + '-';
      let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
      let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
      let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
      let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();

      return Y + M + D + h + m + s;
    }

    function operationFun(index, operation) {
      if (operation == 'change') {
        nowIndex = index;
        tableFormContainerFun(index);
      }

      if (operation == 'delete') {
        const msg = "确定要删除该商品吗？\n\n（一旦删除无法找回！）请确认！";
        if (confirm(msg) == true) {
          axios.delete('http://localhost:8080/products/deleteProductInformation', {
            params: {
              id: tableData[index].id,
              imagePatch: tableData[index].imagePatch
            }
          }).then(function(res) {
            if (res.data == 'success') {
              getTableDataList();
              alert('删除商品成功！');
            }
          }).catch(function(err) {
            console.log(err);
          });

          return true;
        } else {
          return false;
        }
      }
    }

    searchProductByName.addEventListener('click', () => {
      const searchName = productName.value;
      if (searchName.length) {
         axios.get('http://localhost:8080/products/getProductInformationByName', {
            params: {
              name: searchName
            }
          }).then(function(res) {
            if (res.data.length) {
              trData.innerHTML = renderingStr(res.data);
            } else {
              alert('未查找到相关商品数据！');
            }
          }).catch(function(err) {
            console.log(err);
          });
      } else {
        alert('请输入文字！');
      }
    })

    resetProductByName.addEventListener('click', () => {
      productName.value = '';
      getTableDataList();
    })

    tableBannerAddData.addEventListener('click', () => {
      coverContent.setAttribute('style', 'display: block');
      addFormContent.setAttribute('style', 'display: block');

      coverContent.addEventListener('click', () => {
        const changeTheNameText = document.getElementById('changeTheName').value = '';
        const changeThePriceText = document.getElementById('changeThePrice').value = '';

        coverContent.setAttribute('style', 'display: none');
        addFormContent.setAttribute('style', 'display: none');
      })
    })

    
    function addFormContentFun(form) {
      const formData=new FormData(form);

      const name = formData.get('name');
      const price = formData.get('price');
      const introduce = formData.get('introduce');
      const details = formData.get('details');
      const imagePatch = formData.get('imagePatch');

      return false;
    }

    function showImagesFun(imagePatch) {
      const images = document.createElement('img');
      images.setAttribute('src', imagePatch);

      if (!coverContent.children.length) {
        coverContent.setAttribute('style', 'display: block');
        coverContent.appendChild(images);
      }
      
      coverContent.addEventListener('click', () => {
        coverContent.innerHTML = '';
        coverContent.setAttribute('style', 'display: none');
      })
    }

    function tableFormContainerFun(index) {
      coverContent.setAttribute('style', 'display: block');
      changeFormContent.setAttribute('style', 'display: block');

      coverContent.addEventListener('click', () => {
        const changeTheNameText = document.getElementById('changeTheName').value = '';
        const changeThePriceText = document.getElementById('changeThePrice').value = '';

        coverContent.setAttribute('style', 'display: none');
        changeFormContent.setAttribute('style', 'display: none');
      })
    }

    document.getElementById('submitFormData').addEventListener('click', () => {
        const changeTheNameText = document.getElementById('changeTheName').value;
        const changeThePriceText = document.getElementById('changeThePrice').value;
        
        if (changeTheNameText.length && changeThePriceText.length) {
          axios.get('http://localhost:8080/products/changeProductInformation', {
            params: {
              id: tableData[nowIndex].id,
              name: changeTheNameText,
              price: changeThePriceText
            }
          }).then(function(res) {
            if (res.data == 'success') {
              alert('修改商品成功！');
              location.reload();
            } else {
              alert(res.data);
            }
          }).catch(function(err) {
            console.log(err);
          });
        } else {
          alert('请输入有效内容！');
        }
      })
    
    setTimeout(() => {
      getTableDataList();
    }, 100);

  </script>
</body>
</html>